import 'package:appflutterhomeschool/api/api_service.dart';
import 'package:appflutterhomeschool/api/dio_utils.dart';
import 'package:appflutterhomeschool/model/get_chat_massage_model.dart';
import 'package:appflutterhomeschool/utils/sp_util.dart';
import 'package:appflutterhomeschool/view_model/my_app_view_model.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:provider/provider.dart';

//讨论状态管理
class DiscussViewModel extends ChangeNotifier {
  BuildContext me;
  int notificationId;
  List<GetChatMassageModel> listGetChatMassage;
  String titleText = "";
  MyAppViewModel myAppViewModel;

  TextEditingController textEditingController = TextEditingController();

  DiscussViewModel(this.me, this.notificationId);

  initView() {
    myAppViewModel = Provider.of(me);
    Dio2Utils.getInstance().post(ApiService.getChatMassage, {
      "notification_id": notificationId, //类型：String  必有字段  备注：通知（讨论)id
      "role": SpUtil.getString("role_now") //类型：String  必有字段  备注：通知（讨论)id
    }, (successCallBack) {
      listGetChatMassage = [];
      Map<String, dynamic> mapData = successCallBack["data"];
      if (mapData == null) {
        return;
      }
      titleText = mapData['title'];
      if (mapData["massage_list"] != null) {
        List massageList = mapData["massage_list"];
        if (massageList.length > 0) {
          massageList.forEach((element) {
            listGetChatMassage.add(GetChatMassageModel.fromJson(element));
          });
        }
      }
      notifyListeners();
    }, (errorCallBack) {});
  }

  //发送按钮
  sendOutOnTap() {
    if (textEditingController.text == "") {
      Fluttertoast.showToast(msg: "请输入内容");
      return;
    }
    Map<String, dynamic> map = myAppViewModel.identity
        ? {
            "notification_id": notificationId,
            //类型：String  必有字段  备注：讨论id
            "sender_type": myAppViewModel.identity ? "Teacher" : "Student",
            //类型：String  必有字段  备注：发送者类型（家长：Student,教师：Teacher）
            "msg": textEditingController.text,
            //类型：String  必有字段  备注：发送信息
            "role": SpUtil.getString("role_now"),
          }
        : {
            "notification_id": notificationId,
            //类型：String  必有字段  备注：讨论id
            "sender_type": myAppViewModel.identity ? "Teacher" : "Student",
            //类型：String  必有字段  备注：发送者类型（家长：Student,教师：Teacher）
            "msg": textEditingController.text,
            //类型：String  必有字段  备注：发送信息
            "student_id": myAppViewModel?.studentInformationModel?.subjectId,
            "role": SpUtil.getString("role_now"),
            //类型：String  可有字段  备注：学生id(家长发送时必须携带)
          };

    Dio2Utils.getInstance().post(ApiService.senderChatMassage, map,
        (successCallBack) {
      textEditingController.text = "";
      initView();
      notifyListeners();
    }, (errorCallBack) {});
  }
}
